<?php

namespace app\admin\service;

use app\admin\model\Admin as Model;
use app\lib\exception\Admin as AdminException;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class Admin
{
    //#region 查

    static function getList($param)
    {
        $list = [];
        $where = [];
        if (!empty($param['username'])) {
            $where[] = ['username', 'like', '%' . $param['username'] . '%'];
        }
        if (!empty($param['phone'])) {
            $where[] = ['phone', '=', $param['phone']];
        }

        $total = (new Model)->where($where)->count();
        if ($total > 0) {
            $roles = Role::getList();
            $roles = array_column($roles, 'role_name', 'id');
            $list = (new Model)->field('id,username,status,role_ids,phone,create_time,nickname')->where($where)->page($param['pageNum'], $param['pageSize'])->select();
            foreach ($list as &$item) {
                if ($roles[$item['role_ids']]) {
                    $item['roles'] = $roles[$item['role_ids']];
                } else {
                    throw new AdminException(['msg' => '请确认角色状态']);
                }

            }
        }
//        var_dump($list);exit();
//        $list = (new Db)->name('admin')->where($where)->field('id,username,status,role_ids,phone,create_time,nickname')->paginate($param['pageSize'], false)->each(function ($item, $key) {
//            $roles = (new Db)->name('role')->where([['id', 'in', explode(',', $item['role_ids'])]])->column('role_name');
//            $item['roles'] = implode(' | ', $roles);
//            return $item;
//        });

        return ['data' => $list, 'total' => $total];
    }

    static function get($ids, $visible = []): array
    {
        $data = (new Model)->where('id', $ids)->findOrEmpty();
        if ($data->isEmpty()) {
            throw new AdminException(['msg' => '数据缺失']);
        }
        $data = $data->visible($visible)->toArray();
        return $data;
    }

//#endregion

    /**
     * 添加
     * @param $param
     * @return bool
     * @throws AdminException
     */
    static function doAdd($param): bool
    {
        if (empty($param)) throw new AdminException(['msg' => '数据缺失']);
        if (Model::getByUsername($param['username'])) {
            throw new AdminException(['msg' => '账号已存在']);
        }
        if (Model::getByPhone($param['phone'])) {
            throw new AdminException(['msg' => '联系方式已存在']);
        }
        $data = [];
        $data['status'] = $param['status'];
        $salt = getRandChar(6);
        $data['salt'] = $salt;
        $password = Auth::getEncryptPassword($param['password'], $salt);
        $data['password'] = $password;
        $data['username'] = $param['username'];
        $data['nickname'] = $param['nickname'];
        $data['phone'] = $param['phone'];
        $data['join_ip'] = get_client_ip();
        $data['role_ids'] = $param['role_ids'];
        $data['join_time'] = date('Y-m-d H:i:s');
        $data['create_time'] = date('Y-m-d H:i:s');
        $data['update_time'] = date('Y-m-d H:i:s');
        $data['department_id'] = 0;
        $res = (new Model)->save($data);
        if ($res !== false) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param $param
     * @return bool
     * @throws AdminException
     */
    static function doEdit($param): bool
    {
        if (empty($param)) throw new AdminException(['msg' => '数据缺失']);
        $where = [];
        $where[] = ['username', '=', $param['username']];
        $where[] = ['id', '<>', $param['id']];
        $find = (new Model)->where($where)->findOrEmpty();
        if (!$find->isEmpty()) {
            throw new AdminException(['msg' => '账号已存在']);
        }
        unset($where);
        $where = [];
        $where[] = ['phone', '=', $param['phone']];
        $where[] = ['id', '<>', $param['id']];
        $find = (new Model)->where($where)->findOrEmpty();
        if (!$find->isEmpty()) {
            throw new AdminException(['msg' => '联系方式已存在']);
        }

        if (!empty($param['password'])) unset($param['password']);
        $res = (new Model)->Update($param, ['id' => $param['id']], ['username', 'nickname', 'status', 'role_ids', 'phone']);
        if ($res !== false) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除
     * @param $ids
     * @return bool
     * @throws AdminException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    static function doDelete($ids): bool
    {
        if (empty($ids)) throw new AdminException(['msg' => '数据缺失']);
        $find = (new Model)::find($ids);
        $res = $find->delete();
//        $find = (new model)::onlyTrashed()->find($ids);
//        $res = $find->restore();
        if ($res !== false) {
            return true;
        } else {
            return false;
        }
    }

    static function edit_password($param): bool
    {
        if (empty($param)) throw new AdminException(['msg' => '数据缺失']);
        $admin = (new Model)::find($param['id']);
        $password = Auth::getEncryptPassword($param['password'], $admin->salt);
        if ($admin->password !== $password) {
            throw new AdminException(['msg' => '原密码错误']);
        }
        $new_password = Auth::getEncryptPassword($param['new_password'], $admin->salt);
        $res = (new Model)->Update(['password' => $new_password], ['id' => $param['id']], ['password']);
        if ($res !== false) {
            return true;
        } else {
            return false;
        }
    }
}